package com.ti.demo.configuration;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.ollama.OllamaChatModel;
import org.springframework.boot.http.client.ClientHttpRequestFactoryBuilder;
import org.springframework.boot.http.client.ClientHttpRequestFactorySettings;
import org.springframework.boot.web.client.ClientHttpRequestFactories;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestClient;

import java.time.Duration;

/**
 * @description: com.ti.demo.configuration
 * @Author Triagen
 * @Date 2025/7/18 11:12
 */
@Configuration
public class ChatClientConfiguration {

    /**
     * webFlux 默认使用 RestClient.Builder() 的 DefaultRestClientBuilder 创建 RestClient，
     * 但是 ClientHttpRequestFactory(ReactorClientHttpRequestFactory) 默认10s超时，且无法从外部切入修改
     * demo 使用 ClientHttpRequestFactoryBuilder 构造 ReactorClientHttpRequestFactory 修改默认超时，生产切勿进行此类操作，reactive 编程对于此类堵塞操作应谨慎。
     *
     * @return RestClient.Builder
     */
    @Bean
    public RestClient.Builder restClientBuilder() {
        // 创建自定义的RequestFactory设置
        ClientHttpRequestFactorySettings settings = new ClientHttpRequestFactorySettings(
                ClientHttpRequestFactorySettings.Redirects.FOLLOW_WHEN_POSSIBLE,
                Duration.ofMillis(5000), // 连接超时5秒
                Duration.ofSeconds(60),   // 读取超时60秒
                null
        );

        // 使用自定义设置创建RestClient Builder
        return RestClient.builder()
                .requestFactory(ClientHttpRequestFactoryBuilder.reactor().build(settings));
    }

    @Bean("ollamaChatClient")
    public ChatClient ollamaChatClient(OllamaChatModel ollamaChatModel){
        return ChatClient.builder(ollamaChatModel).build();
    }



}
